<?php

namespace app\common\model;

use think\Model;

class Attachment extends Model
{

    // 开启自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';
    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    // 定义字段类型
    protected $type = [
    ];

    public function setUploadtimeAttr($value)
    {
        return is_numeric($value) ? $value : strtotime($value);
    }

    public static function getMimetypeList()
    {
        $data = [
            "image/*"        => "图片",
            "audio/*"        => "音频",
            "video/*"        => "视频",
            "text/*"         => "文档",
            "application/*"  => "应用",
            "zip,rar,7z,tar" => "压缩包",
        ];
        return $data;
    }

    protected static function init()
    {
        // 如果已经上传该资源，则不再记录
        self::beforeInsert(function ($model) {
            if (self::where('url', '=', $model['url'])->find()) {
                return false;
            }
        });
    }

    /**
     * 微信头像保存至本地
     * @param $url
     * @param string $filename
     * @param int $userId
     * @return string[]
     */
    public function saveAvatar($url,$filename = '',$userId = 0)
    {
        if (trim($url) == '' || stripos($url, request()->domain()) !== false) {
            return array(
                'status'     => false
            );
        }

        $uploadDir = '/avatar/' . date('Ymd',time()) . '/';

        $save_dir = ROOT_PATH . 'public' . $uploadDir;

        if (trim($filename) == '') {//保存文件名
            $filename = time() . '.png';
        }else{
            $filename = $filename . '.png';
        }

        //创建保存目录
        if (!file_exists($save_dir) && !mkdir($save_dir, 0777, true)) {
            return array(
                'status'     => false
            );
        }
        //获取远程文件所采用的方法
        $ch      = curl_init();
        $timeout = 5;
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
        if (defined('CURLOPT_IPRESOLVE') && defined('CURL_IPRESOLVE_V4')) {
            curl_setopt($ch, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
        }
        curl_setopt($ch, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
        $img = curl_exec($ch);
        curl_close($ch);

        $fp2 = @fopen($save_dir . $filename, 'a');
        fwrite($fp2, $img);
        fclose($fp2);

        //保存数据到附件管理
        $params = array(
            'admin_id'    => 0,
            'user_id'     => $userId,
            'filesize'    => filesize($save_dir . $filename),
            'imagewidth'  => '132',
            'imageheight' => '132',
            'imagetype'   => 'png',
            'imageframes' => 0,
            'mimetype'    => 'image/png',
            'url'         => $uploadDir . $filename,
            'uploadtime'  => time(),
            'storage'     => 'local',
            'sha1'        => sha1($url),
        );

        $this->data(array_filter($params));
        $this->save();

        unset($img, $url);
        return array(
            'file_name' => $filename,
            'save_path' => $save_dir . $filename,
            'status'    => true
        );
    }
}
